package com.pan.framework.core.factory.scan;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.stream.Collectors;

public class MyScan {

    private String classPath;
    private HashSet<String> classNameSet;
    private URLClassLoader MyLoader;
    public MyScan(String packagePath){

        classPath = System.getProperty("java.class.path").split(";")[0]+"\\"+packagePath.replaceAll("\\.","\\\\");
        try {
            classNameSet = (HashSet) Files.walk(Paths.get(new URL("file:\\"+classPath).toURI()))
                    .filter(path-> Files.isRegularFile(path))
                    .map(Path::toString)
                    .filter(s->s.endsWith(".class"))
                    .map(s->s.replace(classPath+"\\",""))
                    .map(s->s.replaceAll("\\\\","."))
                    .map(s->s.replace(".class",""))
                    .map(s->packagePath+"."+s)
                    .collect(Collectors.toSet());
            URL url = new URL("file:\\"+classPath);
            MyLoader = new URLClassLoader(new URL[]{url});
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }

    }

    public String getClassPath() {
        return classPath;
    }

    public HashSet<String> getClassNameSet() {
        return classNameSet;
    }

    public URLClassLoader getMyLoader() {
        return MyLoader;
    }

}
